import { Component, OnInit } from '@angular/core';
import { Config } from '../../service/config';
import { NzNotificationService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { HttpServcie } from '../../service/http.service';
import { SafeControlBean } from './bean/safeControlRecord.bean';
import { Router } from '@angular/router';
@Component({
  selector: 'safe-control-record',
  templateUrl: './safeControlRecord.html',
  styleUrls: ['./safeControlRecord.scss']
})
export class SafeControlRecord implements OnInit {

  safeControlBean: SafeControlBean = new SafeControlBean();
  list: any = [];
  //多选框
  allChecked: any = false;
  //多选框
  indeterminate: any = false;
  userId: any;
  qUsedPartyId: any = null;
  total: any = 0;
  partyId: any;
  partyOtion: any = [];
  config = Config;

  checkItems = [
    { label: '设计', value: '1' },
    { label: '制造', value: '2' },
    { label: '安装', value: '3' },
    { label: '改造', value: '4' },
    { label: '维修', value: '5' },
    { label: '使用', value: '6' },
    { label: '气瓶充装', value: '7' },
    { label: '经营', value: '8' },
    { label: '其他', value: '9' }
  ];
  dealWays = [
    { label: '下达监察指令书', value: '1' },
    { label: '实施查封', value: '2' },
    { label: '实施扣押', value: '3' },
    { label: '其他', value: '4' }
  ];
  constructor(
    private _notification: NzNotificationService,
    private fb: FormBuilder,
    private httpServcie: HttpServcie,
    private router: Router
  ) {
    this.userId = JSON.parse(window.localStorage['user']).id;
    this.partyId = JSON.parse(window.localStorage['user']).partyId;
    let partyType = JSON.parse(window.localStorage['user']).partyType;
    if (partyType != 4) {
      this._notification.create('warning', '警告提示', '对不起，您无权限');
      this.router.navigateByUrl('/home/main');
    }
  }

  ngOnInit() {
    this.safeControlBean.pageSize = 10;
    this.safeControlBean.currentPage = 1;
    // this.query();

    this.httpServcie.queryByIdAndTypeList({ partyType: '2' }).subscribe(data => {
      if (data.status == '200') {
        let partyList = data.data;
        if (partyList && partyList.length > 0) {
          partyList.forEach(party => {
            this.partyOtion.push({
              id: party.id,
              partyName: party.partyName
            });
          });
        }
        this.httpServcie.queryByIdAndTypeList({ partyType: '1' }).subscribe(data => {
          if (data.status == '200') {
            let partyList = data.data;
            if (partyList && partyList.length > 0) {
              partyList.forEach(party => {
                this.partyOtion.push({
                  id: party.id,
                  partyName: party.partyName
                });
              });
            }
          }
        });
      }
    });
  }



  // 查询面板
  panels = {
    active: true,
    name: '查询',
    disabled: false,
    childPanel: [
      {
        active: false,
        name: '查询'
      }
    ]
  }

  //table加载数据时
  displayDataChange($event) {
    this.list = $event;
    this.refreshStatus();
  }

  //重置选择框
  refreshStatus() {
    const allChecked = this.list.every(value => value.disabled || value.checked);
    const allUnChecked = this.list.every(value => value.disabled || !value.checked);
    this.allChecked = allChecked;
    this.indeterminate = (!allChecked) && (!allUnChecked);
  }

  //全选
  checkAll(value) {
    if (value) {
      this.list.forEach(data => {
        if (!data.disabled) {
          data.checked = true;
        }
      });
    } else {
      this.list.forEach(data => data.checked = false);
    }
  };


  //分页
  nzPageSizeChange(event) {
    this.safeControlBean.pageSize = event;
    this.safeControlBean.currentPage = 1;
    this.query();

  }

  //输入框的方法
  nzPageIndexChange(event) {
    this.safeControlBean.currentPage = event;
    this.query();
  }

  //当前页
  nzPageIndexClickChange(event) {
    this.safeControlBean.currentPage = event;
    this.query();
  }

  query() {
    let param: any = {
      checkerId: this.userId,
      currentPage: this.safeControlBean.currentPage,
      pageSize: this.safeControlBean.pageSize
    }
    if (this.qUsedPartyId) {
      param.usedPartyId = this.qUsedPartyId;
    }

    this.httpServcie.querySafeControlList(param).subscribe(data => {
      if (data.status == '200') {
        this.list = data.data.list;
        this.total = data.data.total;
      } else if (data.status == '401') {
        this.router.navigateByUrl('/login');
        return;
      } else {
        // 异常
        this._notification.create('error', '错误提示', data.message);
      }

    });
  }

  toExport(id) {
    this.httpServcie.exportSafeControl(id).subscribe(data => {

      console.log(data);
      this.download(data.data.fileUrl, data.data.fileName);
    });
  }



  download(url, name) {
    let link = document.createElement('a');
    let body = document.querySelector('body');

    this.getBlob(this.config.IP + this.config.API.getUpload + url).then(blob => {
      link.href = window.URL.createObjectURL(blob);
      link.download = name;
      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);
      link.click();
      body.removeChild(link);
      window.URL.revokeObjectURL(link.href);
    });
  }

  getBlob(url) {
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'blob';
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response);
        }
      };
      xhr.send();
    });
  }

}
